package cn.edu.sjtu.literature.service.impl;

import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.sjtu.literature.db.DBUtil;
import cn.edu.sjtu.literature.db.mapping.UserResultMappingCallback;
import cn.edu.sjtu.literature.entity.User;
import cn.edu.sjtu.literature.service.UserService;
import cn.edu.sjtu.literature.service.exception.SystemException;
import cn.edu.sjtu.literature.service.exception.UserNotFoundException;
import cn.edu.sjtu.literature.service.exception.UserPasswordInvalidException;

public class UserServiceImpl implements UserService {

	private final Log log = LogFactory.getLog(this.getClass());
	
	@Override
	public User authenticate(String username, String password)
			throws UserNotFoundException, UserPasswordInvalidException {
		
		User user = null;
		try {
			user = DBUtil.querySingle("select * from t_user where username='" + username + "'", new UserResultMappingCallback());
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
			throw new SystemException();
		}
		
		if (user == null) {
			log.debug("user[" + username + "] not found");
			throw new UserNotFoundException();
		}
		
		if (!StringUtils.equals(password, user.getPassword())) {
			log.debug("password not match");
			throw new UserPasswordInvalidException();
		}
		
		// found valid user
		return user;
	}

}
